using System;
using System.Data;
using System.Web;
using BEGDC.CC.BL.CCFlow.EV;
using BEGDC.CC.BL.Common;
using BEGDC.CC.BL.Common.Query;
using BEGDC.CC.Entity;
using BEGDC.Utility.Castle;
using NHibernate;

namespace BEGDC.CC.ExcelTool
{
	/// <summary>
	/// Summary description for ExportEVMeeting.
	/// </summary>
	public class ExportEVMeeting : ICCExcelExport
	{
		private IExcelExport excelExport;
		private string templateName = HttpContext.Current.Server.MapPath(System.Configuration.ConfigurationSettings.AppSettings["EVMeetingTemplate"]);
		private string targetFileName = HttpContext.Current.Server.MapPath(System.Configuration.ConfigurationSettings.AppSettings["ExportPath"]);
		//<--modified by joan 2006--7-01
		private string fileName;
		public ExportEVMeeting(IExcelExport excelExport)
		{
			this.excelExport = excelExport;
		}

		public ExportEVMeeting()
		{
			this.excelExport = new ExcelExportCommom();
		}
		private void GenerateFileName()
		{
			DateTime tmpTime=DateTime.Now;
			this.fileName+=tmpTime.Millisecond.ToString();
			this.fileName+=tmpTime.Second.ToString();
			this.fileName+=tmpTime.Minute.ToString();
			this.fileName+="_MeetingMinutes.xls";
		}
		//-->

		public void GenerateEVMeetingForm( int meetingId )
		{
			this.fileName =meetingId.ToString() + "_" + this.fileName;
			try
			{
				//open the meeting minutes template
				this.excelExport.Open( templateName );

				//generate the excel file
				BEGDC.CC.BL.Common.Query.IQuery queryService = AppContainer.Instance[ServiceConst.QueryService] as BEGDC.CC.BL.Common.Query.IQuery;

				IEV evService = AppContainer.Instance[ServiceConst.EVService] as IEV;			
				EVMeeting meeting = evService.GetEVMeetingByID( meetingId );			
				GenerateMeetingInfo( meeting );			
				GenerateMeetingAttendee(queryService,meetingId);
				GenerateAPList(queryService, meetingId );

				this.fileName=this.fileName.Replace("/","").Replace("\\","").Replace("'","").Replace("\"","");
				this.fileName=this.targetFileName + this.fileName;

				this.excelExport.ExportAs( this.fileName );
			}
			catch(Exception ex)
			{
				BEGDC.Utility.ExceptionManagement.GDCException exp=new BEGDC.Utility.ExceptionManagement.GDCException("export_0001",ex.Message,ex.InnerException);
				throw exp;
			}
			finally
			{
				this.excelExport.Close();
			}

		}

		// Add by FanYe 2007/9/6
		public string GenerateMMLinkFile(int meetingId, string filename)
		{
            string exception = string.Empty;
			this.fileName = filename;
			try
			{
				//open the meeting minutes template
				this.excelExport.Open( templateName );

				//generate the excel file
				BEGDC.CC.BL.Common.Query.IQuery queryService = AppContainer.Instance[ServiceConst.QueryService] as BEGDC.CC.BL.Common.Query.IQuery;

				IEV evService = AppContainer.Instance[ServiceConst.EVService] as IEV;			
				EVMeeting meeting = evService.GetEVMeetingByID( meetingId );			
				GenerateMeetingInfo( meeting );			
				GenerateMeetingAttendee(queryService,meetingId);
				GenerateAPList(queryService, meetingId );

				this.excelExport.ExportAs( this.fileName );
			}
			catch(Exception ex)
			{
                exception = ex.ToString();
				BEGDC.Utility.ExceptionManagement.GDCException exp=new BEGDC.Utility.ExceptionManagement.GDCException("export_0001",ex.Message,ex.InnerException);
				throw ex;
			}
			finally
			{
				this.excelExport.Close();
                
			}
            return exception + "\n\n" + templateName;
		}


		#region <--modified by joan 2006--7-01
		private void GenerateMeetingInfo( EVMeeting meeting )
		{
			if( meeting == null )
				return;
			Excel.Range meetingInfoRange = this.excelExport.MyApp.get_Range("MeetingInfo", Type.Missing);
			meetingInfoRange.Cells[1,3] = meeting.Venue;
			if( meeting.MeetingDate != Nullables.NullableDateTime.Default )
				meetingInfoRange.Cells[2,3] = meeting.MeetingDate.Value.ToString("yyyy-MM-dd");
			meetingInfoRange.Cells[3,3] = meeting.VisitingPurpose;
			meetingInfoRange.Cells[5,3] = meeting.Content;
		}

		private void GenerateMeetingAttendee(BEGDC.CC.BL.Common.Query.IQuery queryService, int meetingId )
		{
			DataTable table = queryService.QueryEVMeetingAttendee( meetingId );
			int rowCount=2;
			if( table != null && table.Rows.Count > 0 )
			{
				Excel.Range asbAttendee = this.excelExport.MyApp.get_Range("ASBAttendee", Type.Missing );


				DataRow[] rows = table.Select("Company='ASB'");
				rowCount=2;
				while (rows.Length> rowCount)
				{
					this.excelExport.MyApp.get_Range(asbAttendee.Cells[2,1],asbAttendee.Cells[2,4]).EntireRow.Copy(Type.Missing);
					this.excelExport.MyApp.get_Range(asbAttendee.Cells[2,1],asbAttendee.Cells[2,4]).EntireRow.Insert(Excel.XlInsertShiftDirection.xlShiftDown, false);
					rowCount++;
				}

				//insert asb attendee
				for( int i=0; i < rows.Length; i++ )
				{
					if (rows[i]["NameEN"] != System.DBNull.Value)
						this.excelExport.MyWorkSheet.get_Range(asbAttendee.Cells[i+1, 1],asbAttendee.Cells[i+1, 1]).Value2 = rows[i]["NameEN"].ToString();
					if (rows[i]["NameCN"] != System.DBNull.Value)
						this.excelExport.MyWorkSheet.get_Range(asbAttendee.Cells[i+1, 2],asbAttendee.Cells[i+1, 2]).Value2 = rows[i]["NameCN"].ToString();
					if (rows[i]["Department"] != System.DBNull.Value)
						this.excelExport.MyWorkSheet.get_Range(asbAttendee.Cells[i+1, 3],asbAttendee.Cells[i+1, 3]).Value2 = rows[i]["Department"].ToString();
					if (rows[i]["Title"] != System.DBNull.Value)
						this.excelExport.MyWorkSheet.get_Range(asbAttendee.Cells[i+1, 4],asbAttendee.Cells[i+1, 4]).Value2 = rows[i]["Title"].ToString();
					
				}
				
				//insert customer attendee
				Excel.Range custAttendee = this.excelExport.MyApp.get_Range("CustomerAttendee", Type.Missing );
				DataRow[] rowCus = table.Select("Company<>'ASB'");

				rowCount=2;
				while (rowCus.Length> rowCount)
				{
					this.excelExport.MyApp.get_Range(custAttendee.Cells[2,1],custAttendee.Cells[2,4]).EntireRow.Copy(Type.Missing);
					this.excelExport.MyApp.get_Range(custAttendee.Cells[2,1],custAttendee.Cells[2,4]).EntireRow.Insert(Excel.XlInsertShiftDirection.xlShiftDown, false);
					rowCount++;
				}

				for( int i=0; i < rowCus.Length; i++ )
				{
					if (rowCus[i]["NameEN"] != System.DBNull.Value)
						this.excelExport.MyWorkSheet.get_Range(custAttendee.Cells[i+1, 1],custAttendee.Cells[i+1, 1]).Value2 = rowCus[i]["NameEN"].ToString();
					if (rowCus[i]["NameCN"] != System.DBNull.Value)	
						this.excelExport.MyWorkSheet.get_Range(custAttendee.Cells[i+1, 2],custAttendee.Cells[i+1, 2]).Value2 = rowCus[i]["NameCN"].ToString();
					if (rowCus[i]["Company"] != System.DBNull.Value)
						this.excelExport.MyWorkSheet.get_Range(custAttendee.Cells[i+1, 3],custAttendee.Cells[i+1, 3]).Value2 = rowCus[i]["Company"].ToString();
					if (rowCus[i]["Title"] != System.DBNull.Value)	
						this.excelExport.MyWorkSheet.get_Range(custAttendee.Cells[i+1, 4],custAttendee.Cells[i+1, 4]).Value2 = rowCus[i]["Title"].ToString();				
				}
				
			}
		}

		private void GenerateAPList(BEGDC.CC.BL.Common.Query.IQuery queryService, int meetingId )
		{
			Excel.Range apListRange = this.excelExport.MyApp.get_Range("APList", Type.Missing );
			int rowCount;

			DataTable apTable = queryService.QueryAPListByMeetingID( meetingId );
			DataTable apOwner;
			string strOwner;
			if( apTable != null && apTable.Rows.Count > 0 )
			{

				rowCount=2;
				while (apTable.Rows.Count> rowCount)
				{
					this.excelExport.MyApp.get_Range(apListRange.Cells[2,1],apListRange.Cells[2,4]).EntireRow.Copy(Type.Missing);
					this.excelExport.MyApp.get_Range(apListRange.Cells[2,1],apListRange.Cells[2,4]).EntireRow.Insert(Excel.XlInsertShiftDirection.xlShiftDown, false);
					rowCount++;
				}

				for( int i=0; i < apTable.Rows.Count; i++)
				{
					if (apTable.Rows[i]["APNo"]!=System.DBNull.Value)
						this.excelExport.MyWorkSheet.get_Range(apListRange.Cells[i+1,1], apListRange.Cells[i+1,1]).Value2 = apTable.Rows[i]["APNo"].ToString();
					if (apTable.Rows[i]["Status"]!=System.DBNull.Value)
						this.excelExport.MyWorkSheet.get_Range(apListRange.Cells[i+1,2], apListRange.Cells[i+1,2]).Value2 = apTable.Rows[i]["Status"].ToString();
					if (apTable.Rows[i]["Description"]!=System.DBNull.Value)
						this.excelExport.MyWorkSheet.get_Range(apListRange.Cells[i+1,3], apListRange.Cells[i+1,3]).Value2 = apTable.Rows[i]["Description"].ToString();
					if( apTable.Rows[i]["DueTime"] != System.DBNull.Value )
						this.excelExport.MyWorkSheet.get_Range(apListRange.Cells[i+1,4], apListRange.Cells[i+1,4]).Value2 = ((DateTime)apTable.Rows[i]["DueTime"]).ToString("yyyy-MM-dd");
					//<--Joan 2008/8/8, AP Owner
					strOwner="";
					apOwner=queryService.GetApPartner(Convert.ToInt32(apTable.Rows[i]["APID"]),"Owner");
					for (int j=0;j<apOwner.Rows.Count;j++)
					{
						strOwner +=apOwner.Rows[j][0].ToString()+ "\n";
					}
					this.excelExport.MyWorkSheet.get_Range(apListRange.Cells[i+1,5], apListRange.Cells[i+1,5]).Value2 = strOwner;
					apOwner.Clear();
					//-->end

					
				}
			}
		}
		#endregion

		#region ICCExcelExport Members

		public void Export(System.Web.UI.Page page, int id)
		{
			
			//generate filename randomly
			GenerateFileName();

			this.GenerateEVMeetingForm( id );

			//write the file to client
			this.excelExport.Export2Client( page, this.fileName, "MeetingMinutes.xls" );
		}

		#endregion
	}
}
